﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Subgurim.Controles;
using System.Drawing;
using ControlHorsetrackNamespace;
using ControlLogNamespace;
using ControlDbNamespace;
using WebMsgBoxNamespace;

public partial class horsetrack : System.Web.UI.Page
{
    #region Properties
  
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
       
        #region Reestablecer eventos
        ControlLog.writeLog("[Page_Load:horsetrack.aspx] Resetting Listeners: ");        
        GMap1.resetListeners();
        GMap1.reset();
        #endregion
        #region PostBacks
        if (IsPostBack)
        {
            // NOTE: the following uses an overload of RegisterClientScriptBlock() 
            // that will surround our string with the needed script tags 
            ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBackPanelDeControl", "var isPostBackPanelDeControl = true;", true);
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] PostBack TRUE"); 
        }
        else
        {
            ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBackPanelDeControl", "var isPostBackPanelDeControl = false;", true);
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] PostBack FALSE");
        }

        #endregion
        #region Setup Inicial
        if (Session["setup"] == null)
        {       //Hacemos cualquier operacion con esete valor de Session
             Session["setup"] = true;
        }
        else
        {
        
        }
        #endregion
       
     

        Cliente objUsuario;
        List<Caballo> lstCaballosDeUsuario;
        ControlDB objConnection = new ControlDB();
        GMap1.enablePostBackPersistence = false;
   
        #region Obtener Usuario
        try
        {
            objUsuario = (Cliente)Session["userLogged"];
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] Usuario: " + objUsuario.intIdUsuario.ToString());
            LabelUltimaActualizacion.Text = objConnection.obtenerUltimaActualizacionUsuario(objUsuario);
        }
        catch(Exception ex)
        {
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] Excepcion cargando usuario: " + ex.Source);          
            Response.Redirect("index.aspx?err=1");                
            return;
        }
        #endregion
       
        #region Obtener Info de Caballos del Usuario
        try
        {
            lstCaballosDeUsuario=objConnection.obtenerDatosCaballo(objUsuario.intIdUsuario);
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] Cantidad de caballos del usuario: " + lstCaballosDeUsuario.Count().ToString());          
        
        }
        catch(Exception ex)
        {

            ControlLog.writeLog("[Page_Load:horsetrack.aspx] Excepcion obteniendo info de caballos: " + ex.Source);
            Response.Redirect("index.aspx?err=2");  
            return;
        }

        #endregion
    
        #region Armar Mapa

        GMap1.addControl(new GControl(GControl.preBuilt.GOverviewMapControl));
        GMap1.addControl(new GControl(GControl.preBuilt.LargeMapControl));
        GMap1.mapType = GMapType.GTypes.Hybrid;
        GMap1.enableScrollWheelZoom = true;
        GMap1.enableServerEvents = true;
     

        
          
        
        try
        {
            GMap1.setCenter(objUsuario.obtenerPosicionCentral().getLatLng(),14);
            //GMap1.setCenter(new GLatLng(Convert.ToDouble(objUsuario.strLatitudCentral), Convert.ToDouble(objUsuario.strLongitudCentral)), 14);
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] Mapa centrado en " + objUsuario.obtenerPosicionCentral().strLatitud + " - " + objUsuario.obtenerPosicionCentral().strLongitud);
        
        }
        catch(Exception ex)
        {
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] Excepcion centrando mapa: " + ex.Message + " Lat=" + objUsuario.obtenerPosicionCentral().strLatitud + "Long=" + objUsuario.obtenerPosicionCentral().strLongitud );         
            Response.Redirect("index.aspx?err=3");  
            return;
        }

        foreach (Caballo objCaballo in lstCaballosDeUsuario)
        {
            GMarker marker;
            try
            {
                marker = new GMarker(new GLatLng(Convert.ToDouble(objCaballo.obtenerPosicionActual().strLatitud), Convert.ToDouble(objCaballo.obtenerPosicionActual().strLongitud)));
                
                 GIcon objBaseIcon = new GIcon();
                 objBaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
                  // baseIcon.iconSize = new GSize(20, 34);
                  objBaseIcon.iconSize = new GSize(35, 38);
                  objBaseIcon.shadowSize = new GSize(37, 34);
                  objBaseIcon.iconAnchor = new GPoint(9, 34);
                  objBaseIcon.infoWindowAnchor = new GPoint(9, 2);
                  // Create a lettered icon for this point using our icon class            
                  GIcon objIcon = new GIcon(objBaseIcon);

                  objIcon.image = "http://www.horsetrack.com.ar/Iconos/Caballo1.png";
                  GMarkerOptions objMarkerOptions = new GMarkerOptions(objIcon);
                marker.options = objMarkerOptions;

                ControlLog.writeLog("[Page_Load:horsetrack.aspx] Agregando caballo en " + objCaballo.obtenerPosicionActual().strLatitud + " - " + objCaballo.obtenerPosicionActual().strLongitud);         
            }
            catch (Exception ex)
            {
                ControlLog.writeLog("[Page_Load:horsetrack.aspx] Excepcion centrando caballo: " + ex.Message + " Lat=" + objCaballo.obtenerPosicionActual().strLatitud + "Long=" + objCaballo.obtenerPosicionActual().strLongitud);
                continue;
            }
            GInfoWindow window = new GInfoWindow(marker, ControlHorsetrack.obtenerCuadroDeTextoDeCaballos(objCaballo, (Trazabilidad)Session["verUltimosPasos" + objCaballo.strIDCaballo]), true);
      
            GMap1.addInfoWindow(window);

            if (Session["verUltimosPasos"+objCaballo.strIDCaballo] != null)
            {         
                Trazabilidad objTrazaUltimosPasos = objConnection.obtenerCaminoCaballo(objCaballo, 10);
                PolygonActionShow objPolygonAction = new PolygonActionShow();
                objTrazaUltimosPasos.dibujarEn(GMap1, objPolygonAction);

            }
        }
       
        #endregion
        
        
        #region Geofences
        try
        {
           
            List<GeoFence> lstGeoFenceDeCliente = new List<GeoFence>();
            lstGeoFenceDeCliente = objConnection.obtenerGeoFences(objUsuario.intIdUsuario);

            ControlLog.writeLog("[Page_Load:horsetrack.aspx] GeoFences encontrados: " + lstGeoFenceDeCliente.Count().ToString());
            
            
            foreach (GeoFence objNewGeoFence in lstGeoFenceDeCliente)
            {
                PolygonActionShow interfaceAction = new PolygonActionShow(); 

                ControlLog.writeLog("[Page_Load:horsetrack.aspx] Agregando Poligono: " + objNewGeoFence.strIdGeoFence);
                                            
                
                GMap1.addPolygon(objNewGeoFence.objPolygon);
                GMap1.addListener(interfaceAction.agregarEvento(objNewGeoFence));
                
            }

            Session["accionBorrarGeoFence"] = null;
        }
        catch(Exception ex)
        {
            ControlLog.writeLog("[Page_Load:horsetrack.aspx] Excepcion agregando poligono: " + ex.Message);
            
        }
         
        #endregion

    }
    protected void buttonMarcarEnMapa_Click(object sender, EventArgs e)
    {
        if (textBoxLatGo.Text == String.Empty)
        {
            WebMsgBox.Show("Ingrese un valor válido para la Latitud");
            return;
        }
        if (textBoxLongGo.Text == String.Empty)
        {
            WebMsgBox.Show("Ingrese un valor válido para la Latitud");
            return;
        }

        try
        {
            GMap1.setCenter(new GLatLng(Convert.ToDouble(textBoxLatGo.Text), Convert.ToDouble(textBoxLongGo.Text)), 14);
        }
        catch(Exception ex)
        {
            ControlLog.writeLog("[buttonMarcarEnMapa_Click:horsetrack.aspx] Excepcion centrando mapa: " + ex.Message); 
            WebMsgBox.Show("Los valores son incorrectos. Reviselos y vuelva a intentar la operación");
        }
    }
    protected void buttonVolverACasa_Click(object sender, EventArgs e)
    {
        Cliente objUsuario;
        #region Obtener Usuario
        try
        {
            objUsuario = (Cliente)Session["userLogged"];
        }
        catch (Exception ex)
        {
            ControlLog.writeLog("[buttonVolverACasa_Click:horsetrack.aspx] Excepcion cargando usuario: " + ex.Message);        
            return;
        }
        #endregion

        try
        {
            GMap1.setCenter(objUsuario.obtenerPosicionCentral().getLatLng(), 14);
        }
        catch(Exception ex)
        {
            ControlLog.writeLog("[buttonVolverACasa_Click:horsetrack.aspx] Excepcion centrando mapa: " + ex.Message  ); 
            WebMsgBox.Show("Los valores son incorrectos. Reviselos y vuelva a intentar la operación");
        }
    }

    protected void buttonConfirmaCerrarSesion_Click(object sender, EventArgs e)
    {
        Session.Clear();
        Response.Redirect("index.aspx");
        return;
    }

    protected void imageButtonDibujarPoligono_Click(object sender, ImageClickEventArgs e)
    {    
        try
        {
            PolygonActionCreate objCreatePolygon = new PolygonActionCreate();
            GeoFence objNuevoGeoFence = new GeoFence();
            objNuevoGeoFence.DibujarEn(GMap1, objCreatePolygon,true,true);
                 
        }
        catch(Exception ex)
        {
            ControlLog.writeLog("[imageButtonDibujarPoligono_Click:horsetrack.aspx] Excepcion: "+ex.Message);
            WebMsgBox.Show("Error dibujando: " + ex.Message);    
        }
     

    }

    protected string GMap1_ServerEvent(object s, GAjaxServerEventOtherArgs e)
    {
        ControlDB objConnection = new ControlDB();
   
        switch (e.eventName)
        {
            case "saveGeoFence":

                ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] TODO: Crear Poligono OK ");
                #region Guardar GeoFence
                GeoFence objNewGeoFence = new GeoFence();
                int intCantidadAristas = 0;
                try 
                {
                    intCantidadAristas = Convert.ToInt32(e.eventArgs[0].ToString());
                }
                catch(Exception ex)
                {
                    ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] Excepcion levantando cantidad de aristas: " + ex.Message);
                    WebMsgBox.Show("Error guardando GeoFence 1: "+ex.Message);
                    return string.Empty; 
                }

                try
                {
                    /*
                    objNewGeoFence.objPolygon.PolygonID = e.eventArgs[1].ToString();
                    objNewGeoFence.strArea = e.eventArgs[2].ToString();
                    for (int i = 0; i < intCantidadAristas; i++)
                    {
                        objNewGeoFence.addCoordinates(e.eventArgs[3 + i].ToString().Substring(1, e.eventArgs[3 + i].ToString().IndexOf(',') - 1), e.eventArgs[3 + i].ToString().Substring(e.eventArgs[3 + i].ToString().IndexOf(',') + 1, e.eventArgs[3 + i].ToString().IndexOf(')') - (e.eventArgs[3 + i].ToString().IndexOf(',') + 1)));
                    }
                     * */
                }
                catch(Exception ex)
                {
                    ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] Excepcion guardando aristas: " + ex.Message);
                    WebMsgBox.Show("Error guardando GeoFence 2: " + ex.Message);
                    return string.Empty; 
                }

                try
                {
                    Cliente objUsuario = (Cliente)Session["userLogged"];
                    objNewGeoFence.AddInfo(objUsuario.intIdUsuario.ToString(), "Descripcion de PRUEBA HARDCODED", objUsuario.intIdUsuario.ToString().PadLeft(20, '0') + System.DateTime.Now.Day.ToString().PadLeft(2, '0') + System.DateTime.Now.Month.ToString().PadLeft(2, '0') + System.DateTime.Now.Year.ToString().PadLeft(4, '0') + System.DateTime.Now.Hour.ToString().PadLeft(2, '0') + System.DateTime.Now.Minute.ToString().PadLeft(2, '0') + System.DateTime.Now.Second.ToString().PadLeft(2, '0'));
                    
                }
                catch(Exception ex)
                {
                    ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] Excepcion agregando info de GeoFence: " + ex.Message);
                    WebMsgBox.Show("Error guardando GeoFence 3: " + ex.Message);
                    return string.Empty; 
                }

                try
                {
                    /*
                    string strIdPoligonoCreado = objConnection.crearGeoFence(objNewGeoFence);
                    for (int i = 0; i < intCantidadAristas; i++)
                    {
                        Coordenada objCoordenada = new Coordenada();
                        objCoordenada.strLongitud = e.eventArgs[3 + i].ToString().Substring(1, e.eventArgs[3 + i].ToString().IndexOf(',') - 1);
                        objCoordenada.strLatitud = e.eventArgs[3 + i].ToString().Substring(e.eventArgs[3 + i].ToString().IndexOf(',') + 1, e.eventArgs[3 + i].ToString().IndexOf(')') - (e.eventArgs[3 + i].ToString().IndexOf(',') + 1));
                        objConnection.guardarCoordenada(objCoordenada, strIdPoligonoCreado);
                    }
                     * */
           
                    
                    
                }
                catch (Exception ex)
                {
                    ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] Excepcion guardando GeoFence en DB: " + ex.Message);
                    WebMsgBox.Show("Error guardando GeoFence 4: " + ex.Message);
                    return string.Empty; 
                }
#endregion
                break;
            case "deleteGeoFence":
                #region Borrar GeoFence
                try
                {
                    objConnection.borrarGeoFence(e.eventArgs[0].ToString());
                    Response.Redirect("www.horsetrack.com.ar");
                }
                catch(Exception ex)
                {
                    ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] Excepcion borrando GeoFence:"+ex.Message);
                }
                
                #endregion
                break;
            case "showHorseTrack":
                #region Mostrar Ultimos Pasos
                try
                {
                    Caballo objCaballo = new Caballo();
                    objCaballo.strIDCaballo = e.eventArgs[0].ToString();

                    if (Session["verUltimosPasos" + objCaballo.strIDCaballo] == null)
                    {
                        ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] showHorseTrack: Ver ultimos pasos para: " + e.eventArgs[0].ToString());

                        Session["verUltimosPasos" + objCaballo.strIDCaballo] = objConnection.obtenerCaminoCaballo(objCaballo, 10);

                    }
                    else
                    {
                        ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] showHorseTrack: Reinicializando vista de ultimos pasos para: " + e.eventArgs[0].ToString());

                        Session["verUltimosPasos" + objCaballo.strIDCaballo] = null;
                    }
                }
                catch(Exception ex)
                {
                    ControlLog.writeLog("[GMap1_ServerEvent:horsetrack.aspx] showHorseTrack: Excepcion armando trazado: "+ex.Message);
                }

                #endregion
                break;
        }

        return string.Empty;
    }


    protected void imageButtonDibujarCheckPoint_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            GeoCheckPoint objNuevoGeoCheckPoint = new GeoCheckPoint();
            objNuevoGeoCheckPoint.DibujarEn(GMap1);
        }
        catch(Exception ex)
        {
            ControlLog.writeLog("[imageButtonDibujarCheckPoint_Click:horsetrack.aspx] Excepcion: " + ex.Message);
            WebMsgBox.Show("Error dibujando: " + ex.Message);    
        }
    }
    protected void imageButtonBorrarCheckPoint_Click(object sender, ImageClickEventArgs e)
    {
        Session["accionBorrarCheckPoint"] = true;
    }
    protected void imageButtonAsociarCaballoACerca_Click(object sender, ImageClickEventArgs e)
    {

    }
    protected void imageButtonDesasociarCaballoACerca_Click(object sender, ImageClickEventArgs e)
    {

    }
    protected void btnCambiarPassword_Click(object sender, EventArgs e)
    {
        if (idModifPass.Text != idModifRepitePass.Text)
        {
            WebMsgBox.Show("Th new password is not equal to the confirmed password. Check and try again");
        }
        else
        {
            Cliente objUsuario = (Cliente)Session["userLogged"];            
            ControlDB conn = new ControlDB();
            if (conn.CambiarPassword(objUsuario, idModifPass.Text))
            {
                WebMsgBox.Show("Password changed successfully!");
            }
            else
            {
                WebMsgBox.Show("We are sorry. We couldn't change the password. Please notice us about your situation in order to finish your requirement. Thanks you for you patience!");
            }
            
        }
    }
}